<?php

use think\Db;

/**
 * 获取分类所有子分类
 * @param int $cid 分类ID
 * @return array|bool
 */
function get_category_children($cid)
{
    if (empty($cid)) {
        return false;
    }

    $children = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->select();

    return array2tree($children);
}

/**
 * 根据分类ID获取文章列表（包括子分类）
 * @param int   $cid   分类ID
 * @param int   $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}

/**
 * 根据分类ID获取文章列表，带分页（包括子分类）
 * @param int   $cid       分类ID
 * @param int   $page_size 每页显示条数
 * @param array $where     查询条件
 * @param array $order     排序
 * @param array $filed     查询字段
 * @return bool|\think\paginator\Collection
 */
function get_articles_by_cid_paged($cid, $page_size = 15, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->paginate($page_size);

    return $article_list;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}

/**
 * 正整数检查
 * @param int $num
 * @return bool
 */
function isNum($num){
    $pattern = "/^[1-9]*[1-9][0-9]*$/";
    if (preg_match($pattern, $num)) {
        return true;
    } else {
        return false;
    }
}
/**
 * 金额检查
 * @param int $num
 * @return bool
 */
function isMoney($num){
        if (preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $num) && $num > 0) {  
            return true;  
        }else{   
            return false;
        } 
    }
/**
 * 传递数据以易于阅读的样式格式化后输出
 * @param mixed $data
 * @return string
 */
function p($data){
    // 定义样式
    $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
    // 如果是boolean或者null直接显示文字；否则print
    if (is_bool($data)) {
        $show_data=$data ? 'true' : 'false';
    }elseif (is_null($data)) {
        $show_data='null';
    }else{
        $show_data=print_r($data,true);
    }
    $str.=$show_data;
    $str.='</pre>';
    echo $str;
}


/**
 * 时间戳转换成日期
 * @param int $time
 * @return string
 */
function date_time($time)
{
    return date('Y-m-d H:i:s', $time);
}


/**
 * 钱包类型
 * @return array
 */
function wallet_type(){
    $type[0] = '';
    $type[1] = '激活积分';
    $type[2] = '已释放激活积分';
    $type[3] = '消费积分';
    $type[4] = '已释放消费积分';
    $type[5] = '分享积分';
    $type[6] = '已释放分享积分';
    $type[7] = '增值宝';
    $type[8] = '商家账户';
    $type[9] = '在线支付';
    return $type;
}

/**
 * 提现状态
 * @return array
 */
function status_type(){
    $type[100] = '待处理';
    $type[1] = '提现成功';
    $type[2] = '拒绝提现';
    return $type;
}

/**
 * 资金变动类型
 * @return array
 */
function change_type(){
    $type[1] = '激活等级';
    $type[2] = '会员转出';
    $type[3] = '会员转入';
    $type[4] = '线下消费收钱';
    $type[5] = '线下消费支出';
    $type[6] = '提现';
    $type[7] = '拒绝提现';
    $type[8] = '积分释放';
    $type[9] = '增值宝增值';
    $type[10] = '分享奖励';
    $type[11] = '推荐商户提成';
    $type[12] = '激活等级赠送激活积分';
    $type[13] = '增值宝充值';
    $type[14] = '重消';
    $type[15] = '等级激活支付';
    $type[16] = '后台操作';
    $type[17] = '注册领红包';
    return $type;
}

/**
 * 提示信息
 * @param int       $status     0错误 1正确
 * @param string    $message    提示信息
 * @param string    $url        跳转地址
 * @return json
 */
function  show($status, $message,$url='') {
    $reuslt = array(
        'status' => $status,
        'message' => $message,
        'url' => $url,
    );
    exit(json_encode($reuslt));
}

/**
 * 截取文章标题
 * @param string    $str        字符串
 * @param int       $len        控制长度
 * @return string
 */
function GetPartStr($str,$len)
{
    $one=0;
    $partstr='';
    for($i=0;$i<$len;$i++){ 
        $sstr=substr($str,$one,1);
        if(ord($sstr)>224){
            $partstr.=substr($str,$one,3);
            $one+=3;
        }elseif(ord($sstr)>192){
            $partstr.=substr($str,$one,2);
            $one+=2;
        }elseif(ord($sstr)<192){
            $partstr.=substr($str,$one,1);
            $one+=1;
        }
    }
    if(strlen($str)<=$one){
       return $partstr;
    }else{
        return $partstr.'....';
    }
}

/**
 * 截取银行卡后四位
 * @param int       $card_id    银行卡号
 * @return string
 */
function  cut_card_id($card_id) {
    return(substr($card_id,-4));
}

/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function request_post($param = '',$url = '') {
    //$url = 'https://openapi.caibaopay.com/gatewayOpen.htm';
    $url = 'http://openapi.caibaopay.com/gatewayOpen.htm';
    if (empty($url) || empty($param)) {

        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    
    return $data;
}

/*
*处理Excel导出
*@param $datas array 设置表格数据
*@param $titlename string 设置head
*@param $title string 设置表头
*/
function excelData($datas,$titlename,$title,$filename){
    $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
    $str .="<table border=1>".$titlename;
    $str .= $title;
    foreach ($datas  as $key=> $rt )
    {
        $str .= "<tr>";
        foreach ( $rt as $k => $v )
        {
            $str .= "<td>{$v}</td>";
        }
        $str .= "</tr>\n";
    }
    $str .= "</table></body></html>";
    header( "Content-Type: application/vnd.ms-excel; name='excel'" );
    header( "Content-type: application/octet-stream" );
    header( "Content-Disposition: attachment; filename=".$filename );
    header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    header( "Pragma: no-cache" );
    header( "Expires: 0" );
    exit( $str );
}
